package cn.mxh.pethspt.service.impl;

import cn.mxh.pethspt.dao.DingDao;
import cn.mxh.pethspt.dao.impl.DingDaoImpl;
import cn.mxh.pethspt.entity.Ding;
import cn.mxh.pethspt.service.DingService;
import cn.mxh.pethspt.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DingServiceImpl implements DingService {
    DingDao dingDao = new DingDaoImpl();

    /**
     * 添加交易订单
     *
     * @param ding
     * @return
     */
    @Override
    public boolean add(Ding ding) throws SQLException {
        Connection connection = null;
        int num = 0;
        try{
            connection = DruidUtils.getConnection();
            connection.setAutoCommit(false);// 关闭事物控制
            num = dingDao.add(ding);
            if(num == 1){// 新增订单总表成功
                connection.commit();// 提交
            }
        } catch (Exception e){
            connection.rollback();// 不提交
            e.printStackTrace();
        } finally {
            DruidUtils.close();
        }
        return (num == 1);
    }

    /**
     * 修改订单详情
     *
     * @param ding
     * @return
     * @throws Exception
     */
    @Override
    public boolean update(Ding ding) throws Exception {
        Connection connection = null;
        int num = 0;
        try{
            connection = DruidUtils.getConnection();
            connection.setAutoCommit(false);// 关闭事物控制
            num = dingDao.update(ding);
            if(num == 1){// 新增订单总表成功
                connection.commit();// 提交
            }
        } catch (Exception e){
            connection.rollback();// 不提交
            e.printStackTrace();
        } finally {
            DruidUtils.close();
        }
        return (num == 1);
}

    /**
     * 查询所有订单
     *
     * @return
     */
    @Override
    public List<Ding> getAll() {
        Connection conn = null;
        List<Ding> dingList = new ArrayList<>();
        try{
            conn = DruidUtils.getConnection();
            dingList = dingDao.getAll();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DruidUtils.close(conn);
        }
        return  dingList;
    }

    /**
     * 根据订单id查询
     *
     * @param dingId
     * @return
     */
    @Override
    public Ding getDingByid(Integer dingId) {
        Connection conn = null;
        Ding ding = null;
        try{
            conn = DruidUtils.getConnection();
            ding = dingDao.getDingBydingId(dingId);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DruidUtils.close(conn);
        }
        return ding;
    }
}
